/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { CurvedBaseCommand, FeaturedCmdDialogParams } from '@app-cad/types';
import i18n from 'i18next';
import { pickedFaceData } from '@amcax/base';
import { RJSFSchema } from '@rjsf/utils';
import { useEffect, useState } from 'react';
import { PickInputRJSFFormat } from '@app-base/common/components/command-form/constants';
import { useTools } from '@app-base/common/hooks/useTools';
import { useCommand } from '@app-base/common/hooks/useCommand';
import { PickableCommandForm } from '@app-base/common/components/command-form/pickable';

type Params = {
  base: string;
  faces: string[];
};

type FormData = {
  faces: pickedFaceData; // 暂时设定为只有一个面
};

interface FaceCommandProps {
  cmdID: string;
  cmdName: string;
  facesPlaceholder: string;
}

export function CmdRepairFace({
  title,
  onClose,
  props,
  cmdID,
  cmdName,
  facesPlaceholder,
}: FeaturedCmdDialogParams & FaceCommandProps) {
  const [formData, setFormData] = useState<FormData>();

  const { picker } = useTools();

  useEffect(() => {
    if (!props?.params) {
      setFormData(null);
      return () => {};
    }

    const params: Params = props.params;
    const { base, faces } = params;

    const faceIds = faces.map((face) => `${base}:f${face}`);
    initEditDependency(faceIds);

    setFormData({
      faces:
        faceIds && faceIds.length > 0
          ? (picker.generatePickObjByPickID(faceIds[0]) as pickedFaceData)
          : null,
    });
  }, [props?.shape]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);
    onClose();
  };

  useEffect(() => {
    preview();
  }, [formData]);

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand(cmdID, {
      commandName: cmdName,
      editDxid: props?.shape,
      dependencies: props?.params ? [props.params.base] : [],
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { faces } = formData;
    return confirmCommand(
      {
        a: {
          // faces: faces.map((c) => Number(c.meshId.split(':f')[1])),
          // base: faces[0].idInfo.o,
          faces: [Number(faces.meshId.split(':f')[1])],
          base: faces.idInfo.o,
        },
      },
      preview,
    );
  };

  const isFormDataValid = () => {
    return formData?.faces != null;
  };

  const preview = async () => {
    clear();

    if (!isFormDataValid()) {
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      faces: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        faces: {
          'ui:placeholder': facesPlaceholder,
          'ui:autofocus': true,
        },
      }}
      formData={formData}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdRepairFace: CurvedBaseCommand = {
  id: 'CmdRepairFace',
  label: 'command.repair-face',
  icon: 'commands/feature/repair-face',
  create: (label, onClose, props) => (
    <CmdRepairFace
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      cmdID='cmd-repair-face'
      cmdName='CreateHealFace'
      facesPlaceholder='请输入被修复的面'
    />
  ),
};
